package org.huzhp.console.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.huzhp.console.entity.vo.GatewayFilterVo;
import org.huzhp.console.entity.vo.GatewayPredicateVo;
import org.huzhp.console.entity.vo.GatewayRouteVo;

import java.util.*;

/**
 * @Description: java类作用描述
 * @Author: huzp
 * @CreateDate: 2020/3/12 18:28
 * @Version: 1.0
 */
public class RouteUtil {
    private RouteUtil() {
    }

    public static List<GatewayRouteVo> parse(String service) {
        List<GatewayRouteVo> routeVos = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        try {
            Map<String, Object> services = mapper.readValue(service, Map.class);

            List<Map> apps = (List<Map>) ((HashMap) services.get("applications")).get("application");
            apps.forEach(Attempt.apply(map -> routeVos.add(parseRoute(map))));
        } catch (JsonProcessingException e) {
        }
        return routeVos;
    }

    public static GatewayRouteVo buildGatewayRoute(String name) throws JsonProcessingException {
        GatewayRouteVo routeVo = new GatewayRouteVo();
        routeVo.setRouteId(name);
        routeVo.setRouteUri("lb://" + name);
        buildServiceCommon(routeVo);
        return routeVo;
    }

    public static GatewayRouteVo parseRoute(Map route) throws JsonProcessingException {
        return buildGatewayRoute(route.get("name").toString().toLowerCase());
    }

    public static void buildServiceCommon(GatewayRouteVo routeVo) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        GatewayPredicateVo predicateVo = new GatewayPredicateVo();
        predicateVo.setPredicateName("Path");
        Map predicateMap = new HashMap() {{
            put("pattern", "/" + routeVo.getRouteId() + "/**");
        }};
        predicateVo.setPredicateArgsMap(predicateMap);
        predicateVo.setPredicateArgs(mapper.writeValueAsString(predicateMap));
        routeVo.setPredicates(Arrays.asList(new GatewayPredicateVo[]{predicateVo}));
        GatewayFilterVo filterVo = new GatewayFilterVo();
        filterVo.setFilterName("StripPrefix");
        Map filterMap = new HashMap() {{
            put("parts", 1);
        }};
        filterVo.setFilterArgsMap(filterMap);
        filterVo.setFilterArgs(mapper.writeValueAsString(filterMap));
        routeVo.setFilters(Arrays.asList(new GatewayFilterVo[]{filterVo}));
    }

}
